<template>
  <div class="upload-wrapper">
    <div class="upload-select">
      <input
        type="file"
        @change="inputHandleClick"
        multiple
        class="upload-input"
        ref="uploadInput"
      />
      <button class="upload-file" @click="uploadHandleClick" v-if="!imgSrc">
        <i class="iconfont icon-shangchuan"></i>
        <span>仅支持小于1M的JPEG/PNG格式图片</span>
      </button>
      <div
        v-if="imgSrc"
        class="upload-img"
        @mouseover.prevent="mounseoverHandleClick"
        @mouseleave.prevent="mounseleaveHandleClick"
      >
        <img :src="imgSrc" />
        <div class="upload-options" v-show="isShowOption">
          <i class="iconfont icon-preview" title="预览" @click="previewImg"></i>
          <i class="iconfont icon-shanchu" title="删除" @click="deleteImg"></i>
        </div>
      </div>
    </div>
    <PreviewModal :img-src="imgSrc" :is-show-preview.sync="isShowPreview" />
  </div>
</template>

<script>
import PreviewModal from './upload-preview.vue'
import { beforeUploadCheck } from '../utils/helper'
export default {
  props: {
    value: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      imgSrc: '',
      isShowOption: false,
      isShowPreview: false
    }
  },
  components: {
    PreviewModal
  },
  methods: {
    // 点击上传按钮
    inputHandleClick(e) {
      const imgList = Array.from(e.target.files)
      const result = this.uploadCheck(imgList[0])
      if (!result) {
        this.imgSrc = ''
        this.$refs['uploadInput'].value = ''
        return
      }
      const reader = new FileReader()
      reader.readAsDataURL(imgList[0])
      // 读取操作结束时触发
      reader.onloadend = e => {
        this.imgSrc = e.target.result
        this.$emit('success', e.target.result)
      }
    },
    // 点击上传按钮
    uploadHandleClick() {
      this.$refs['uploadInput'].click()
    },
    // 预览图片
    previewImg() {
      this.isShowPreview = true
    },
    // 删除图片
    deleteImg() {
      this.imgSrc = ''
      this.$refs['uploadInput'].value = ''
    },
    // 移入鼠标
    mounseoverHandleClick() {
      this.isShowOption = true
    },
    // 移出鼠标
    mounseleaveHandleClick() {
      this.isShowOption = false
    },
    // 上传检查
    uploadCheck(file) {
      const result = beforeUploadCheck(file, { format: ['image/jpeg', 'image/png'], size: 1 })
      const { error, passed } = result
      if (error === 'format') {
        this.$Message.error('上传图片只能是PNG或者JPG格式')
      }
      if (error === 'size') {
        this.$Message.error('上传图片不能超过1M')
      }
      return passed
    }
  },
  watch: {
    value(val) {
      if (val) this.imgSrc = val
    }
  }
}
</script>
